package com.hmall.order.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Description HandlerInterceptor
 * @Author dmx
 * @Date 2024-11-16
 */
@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<Long> UserThreadLocal = new ThreadLocal();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String truth = request.getHeader("Truth");
        String[] split = truth.split("=");
        //去掉" 2"前的空格
        String trim = split[1].trim();
        //将字符串转换为Long类型
        long id = Long.parseLong(trim);
        UserThreadLocal.set(id);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //响应结束，需清理ThreadLocal中的数据，防止内存泄漏
        UserThreadLocal.remove();
    }

    // 提供一个静态方法，方便其他地方获取用户ID
    public static Long getUserId() {
        return UserThreadLocal.get();
    }
}
